package org.sshbot;

import java.net.UnknownHostException;
import java.util.Locale;

import org.sshbot.transport.SSH;
import org.sshbot.transport.Transport;
import org.sshbot.util.Utils;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.securecrt.SaveSession;
import com.securecrt.pojo.SQLHelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Rlogin extends Activity {

	public static boolean isPortrait = true;

	private Transport transport;
	
	Button btLoginRlogin;
	Button btBack, btHome,btvn,bten,btkr;
	public String Server="192.168.1.5";
	EditText hostname;
	EditText username;
	Spinner protocol;
	TextView tvprotocol,tvHostname,tvUsername,tvlinksession;
	CheckBox save_session;
	ProgressDialog pro;
	private boolean checked=false;
	SQLHelper eventsData;

	Session session;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rlogin);
        
        protocol = (Spinner)findViewById(R.id.protocol);
        hostname=(EditText)findViewById(R.id.hostname);
        username=(EditText)findViewById(R.id.username);
        btLoginRlogin=(Button)findViewById(R.id.btLoginRlogin);
        
        btBack = (Button) findViewById(R.id.btBack);
		btHome = (Button) findViewById(R.id.btHome);
		btBack.setOnClickListener(onBackClick());
		btHome.setOnClickListener(onHomeClick());
               
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.protocol ,android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        protocol.setAdapter(adapter);
        protocol.setSelection(1);
        protocol.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String name = parent.getItemAtPosition(position).toString();
				if(name.equals("rlogin")){
					return;
				}
				String classSelected = "org.sshbot." + name.toUpperCase();
				Intent intent = new Intent(classSelected);
				startActivity(intent);
				finish();
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
        btLoginRlogin.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					OpenTerminal();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
        	
        });
		tvprotocol=(TextView)findViewById(R.id.tvprotocol);
		tvHostname=(TextView)findViewById(R.id.tvHostname);
		tvUsername=(TextView)findViewById(R.id.tvUsername);
		save_session=(CheckBox)findViewById(R.id.save_session);
		
        btvn=(Button)findViewById(R.id.btvn);btvn.setOnClickListener(onClickbtvn());
        bten=(Button)findViewById(R.id.bten);bten.setOnClickListener(onClickbten());
        btkr=(Button)findViewById(R.id.btkr);btkr.setOnClickListener(onClickbtkr());
        tvlinksession=(TextView)findViewById(R.id.tvlinksession);
        tvlinksession.setOnClickListener(OnClickLinksession);
        eventsData=new SQLHelper(this);
    }
    private void passSaveSession(){
    	Intent i=new Intent(this, SaveSession.class);
    	i.putExtra("host",tvHostname.getText().toString());
		i.putExtra("user", String.valueOf(tvUsername.getText().toString()));
    	startActivity(i);
    }
    private OnClickListener OnClickLinksession=new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			passSaveSession();
		}
	};
    private void refresh() {
        finish();
        Intent myIntent = new Intent(Rlogin.this, Rlogin.class);
        startActivity(myIntent);
    }
    private void changuageLang(String lang){
		Locale locale=new Locale(lang);
        Locale.setDefault(locale);
        Configuration config=new Configuration();
        config.locale=locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }
    private OnClickListener onClickbtvn(){
    	OnClickListener onClickbtvn=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("vn");refresh();
			}
		};
    	return onClickbtvn;
    }
    private OnClickListener onClickbten(){
    	OnClickListener onClickbten=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("en");refresh();
			}
		};
    	return onClickbten;
    }

    private OnClickListener onClickbtkr(){
    	OnClickListener onClickbtkr=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("kr");refresh();
			}
		};
    	return onClickbtkr;
    }
    private void saveSessionActive(){
    	SQLiteDatabase db=eventsData.getWritableDatabase();
		ContentValues values=new ContentValues();
		values.put(SQLHelper.HOSTNAME, tvHostname.getText().toString());
		values.put(SQLHelper.USERNAME, String.valueOf(tvUsername.getText().toString()));
		db.insert(SQLHelper.SESSION, null, values);
    }
    private void OpenTerminal() throws UnknownHostException{
    	loadingShow();
    	if(hostname.getText().toString().trim().equals("")){
    		Toast.makeText(this, "Server name is not empty!", Toast.LENGTH_LONG).show();
    		return;
		}
    	if(username.getText().toString().trim().equals("")){
    		Toast.makeText(this, "Username is not empty!", Toast.LENGTH_LONG).show();
    		return;
		}
    	
    	Editor ed=this.getPreferences(0).edit();
    	ed.putString("server", hostname.getText().toString());
    	ed.putString("username", username.getText().toString());
    	ed.commit();
    	
    	boolean res = connectToServer(hostname.getText().toString(), username.getText().toString());
		if (res) {
			if(checked){
				//save session
				saveSessionActive();
			}				
			
    	}else{
    		Utils.showErrorMessage(this,"rLogin Connect Fault.");    		
    		//Toast.makeText(this, "That bai", Toast.LENGTH_LONG).show();
    		return;
    	}
    	
    	
    }
    private void loadingShow(){
    	pro=ProgressDialog.show(this, "", "Please wait...");
    	
    }
      
    
	private OnClickListener onBackClick() {
		OnClickListener onBackClick = new OnClickListener() {
			@Override
			public void onClick(View v) {
				//moveTaskToBack(true);
				finish();
				System.exit(0);
			}
		};
		return onBackClick;
	}
	
	private OnClickListener onHomeClick() {
		OnClickListener onHomeClick = new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
				System.exit(0);

			}
		};
		return onHomeClick;
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// TODO save this to somewhere better place
		isPortrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		
//		transport.disconnect();
	}

	
		private SSH sh;
		private boolean connectToServer(final String host, final String username) throws UnknownHostException {
			
			transport = null;
			sh = null;
			try {
				sh = new SSH(username,"", host, 0);			
			} catch (JSchException e) {
				e.printStackTrace();			
			}

			if(sh.isConnected()){
				transport = sh;
			}else{
				return false;
			}
			
			if (transport != null) {
				TerminalView tv = new TerminalView(this, transport);
				
				setContentView(tv);
			}

			return true;
		}
}
